<template>
  <div class="clothes-category-view">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-icon name="arrow-left" class="back-button" @click="handleBack" />
      <h1 class="title">我的衣橱</h1>
    </div>

    <!-- 一级分类选择区域 -->
    <div class="category-section">
      <div
        v-for="category in categories"
        :key="category"
        class="category-item"
        :class="{ active: currentCategory === category }"
        @click="handleCategoryChange(category)"
      >
        <div class="category-icon">
          <img
            :src="`/src/assets/icons/${getCategoryIcon(category)}`"
            alt="分类图标"
          />
        </div>
        <div class="category-name">{{ category }}</div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content-wrapper">
      <!-- 左侧二级分类 -->
      <div class="secondary-categories">
        <div
          v-for="subCategory in subCategories"
          :key="subCategory"
          :class="[
            'sub-category-item',
            { active: selectedSubCategory === subCategory },
          ]"
          @click="handleSubCategorySelect(subCategory)"
        >
          {{ subCategory }}
        </div>
      </div>

      <!-- 右侧衣物展示 -->
      <div class="clothes-grid">
        <div
          v-for="clothes in filteredClothes"
          :key="clothes._id"
          class="clothes-item"
          @click="handleClothesSelect(clothes)"
        >
          <div class="clothes-image">
            <img
              :src="clothes.imageUrl || clothes.imageUrls[0]"
              :alt="clothes.name"
            />
          </div>
        </div>

        <!-- 空状态 -->
        <div
          v-if="filteredClothes.length === 0 && !loading"
          class="empty-state"
        >
          <img
            src="/src/assets/icons/emptytest.svg"
            alt=""
            style="width: 75%"
          />
          <p>暂无数据</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <van-loading type="spinner" />加载中...
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useClothesStore } from "../store/clothes";
import { useOutfitStore } from "../store/outfit";

import { clothesCategories, getCategoryIcon } from "../utils/clothesCategory";
import { showToast } from "vant";

const router = useRouter();
const route = useRoute();
const outfitStore = useOutfitStore();
const clothesStore = useClothesStore();

// 服装分类数据
const categories = ref([
  "上衣",
  "下装",
  "裙子",
  "外套",
  "鞋子",
  "配饰",
  "运动装",
  "家居服",
]);

// 获取URL参数中的一级分类名称，如果不存在或不在分类列表中，使用第一个分类
const currentCategory = ref(
  route.params.categoryId && categories.value.includes(route.params.categoryId)
    ? route.params.categoryId
    : categories.value[0]
);
const loading = ref(false);

// 初始化二级分类数据
const subCategories = ref(["全部"]);
const selectedSubCategory = ref("全部");

// 加载二级分类
const loadSubCategories = async () => {
  try {
    // 获取当前一级分类信息
    const categoryInfo = clothesCategories.find(
      (cat) => cat.text === currentCategory.value
    );

    // 如果找到了分类信息且有children，使用实际的子分类
    if (
      categoryInfo &&
      categoryInfo.children &&
      categoryInfo.children.length > 0
    ) {
      // 创建二级分类列表，添加'全部'选项
      const categorySubs = [
        "全部",
        ...categoryInfo.children.map((child) => child.text),
      ];
      subCategories.value = categorySubs;
    } else {
      // 否则使用基础的二级分类列表
      subCategories.value = ["全部"];
    }

    // 重置选中的二级分类为'全部'
    selectedSubCategory.value = "全部";
  } catch (error) {
    console.error("加载子分类失败:", error);
  }
};

// 加载衣物数据和子分类
const loadData = async () => {
  try {
    loading.value = true;

    // 从store获取所有衣物
    if (clothesStore.clothesList.length === 0) {
      await clothesStore.fetchClothesList();
    }

    // 加载二级分类
    await loadSubCategories();
  } catch (error) {
    console.error("加载数据失败:", error);
    showToast("加载失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 页面挂载时加载数据
onMounted(async () => {
  await loadData();
});

// 监听路由参数变化
watch(
  () => route.params.categoryId,
  async (newCategory) => {
    if (newCategory && categories.value.includes(newCategory)) {
      currentCategory.value = newCategory;
      selectedSubCategory.value = "全部";
      await loadData();
    }
  },
  { immediate: true }
);

// 计算属性：根据选中的二级分类筛选衣物
const filteredClothes = computed(() => {
  // 首先从store获取clothesList中属于当前一级分类的衣物
  let clothesList = clothesStore.clothesList.filter((item) => {
    // 处理type为数组的情况
    if (Array.isArray(item.type) && item.type.length > 0) {
      return item.type.some((t) => {
        // 检查t是否有text属性
        if (typeof t === "object" && t.text) {
          return t.text === currentCategory.value;
        }
        // 处理字符串类型的情况
        return t === currentCategory.value;
      });
    }
    // 处理type为字符串的情况
    return item.type === currentCategory.value;
  });

  // 根据二级分类筛选
  if (selectedSubCategory.value !== "全部") {
    clothesList = clothesList.filter((item) => {
      // 处理type为数组的情况
      if (Array.isArray(item.type) && item.type.length > 0) {
        return item.type.some((t) => {
          // 检查t是否有text属性
          if (typeof t === "object" && t.text) {
            return t.text === selectedSubCategory.value;
          }
          // 处理字符串类型的情况
          return t === selectedSubCategory.value;
        });
      }
      // 如果没有子分类数据，返回所有衣物
      return true;
    });
  }

  return clothesList;
});

// 处理返回按钮点击
const handleBack = () => {
  router.back();
};

// 处理一级分类切换
const handleCategoryChange = (category) => {
  currentCategory.value = category;
  selectedSubCategory.value = "全部";
  loadData();
};

// 处理二级分类选择
const handleSubCategorySelect = (subCategory) => {
  selectedSubCategory.value = subCategory;
};

// 处理衣物选择
const handleClothesSelect = async (clothes) => {
  // 这里可以添加衣物选择逻辑，例如添加到搭配中
  // console.log("选择衣物:", clothes._id);
  // 选择后返回上一页
  await getClothesDetail(clothes._id);
  router.back();
};

// 根据id查询单个衣物详情
const getClothesDetail = async (clothesId) => {
  try {
    const clothes = await clothesStore.fetchClothesDetail(clothesId);

    if (!clothes) {
      return console.error("衣物不存在");
    }

    outfitStore.addToTempStorage(clothes);
  } catch (error) {
    console.error("获取衣物详情失败:", error);
  }
};
</script>

<style scoped>
.clothes-category-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fbfbfb;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  /* background-color: #ffffff; */
  position: sticky;
  top: 0;
  z-index: 100;
  position: relative;
}

.back-button {
  font-size: 18px;
  cursor: pointer;
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #6c63ff;
  flex: 1;
  text-align: center;
}

/* 一级分类区域 */
.category-section {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  /* padding: 12px 8px; */
  /* border-bottom: 1px solid #f5f5f5; */
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.category-section::-webkit-scrollbar {
  display: none;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* margin: 0 16px; */
  padding: 16px 26px;
  cursor: pointer;
  transition: transform 0.2s;
  gap: 5px;
}

/* .category-item:hover {
  transform: translateY(-2px);
} */

.category-item.active .category-name {
  color: #6c63ff;
  /* font-weight: 600; */
}

.category-icon {
  /* width: 40px;
  height: 40px; */
  display: flex;
  align-items: center;
  justify-content: center;
  /* margin-bottom: 8px; */
}

.category-icon img {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.category-name {
  font-size: 12px;
  color: #000000;
}

/* 主内容区域 */
.content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
  box-shadow: 0 0 7px rgba(0, 0, 0, 0.1);
}

/* 左侧二级分类 */
.secondary-categories {
  width: 25%;
  /* background-color: #ffffff; */
  overflow-y: auto;
  /* border-right: 1px solid #f0f0f0; */
  padding: 0;
}

.sub-category-item {
  padding: 16px 12px;
  text-align: left;
  cursor: pointer;
  transition: all 0.2s;
  /* border-bottom: 1px solid #f5f5f5; */
  color: #333333;
  font-size: 14px;
}

.sub-category-item:hover {
  background-color: #f9f9f9;
}

.sub-category-item.active {
  color: #6c63ff;
  /* font-weight: 600; */
  /* background-color: transparent; */
  border-left: 3px solid #6c63ff;
  background-color: #ffffff;
}

/* 右侧衣物展示 */
.clothes-grid {
  width: 75%;
  padding: 8px 16px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  background-color: #ffffff;
  min-height: 0;
}

.clothes-item {
  background-color: #ffffff;
  cursor: pointer;
  transition: transform 0.2s;
  /* padding: 8px; */
}

.clothes-item:hover {
  transform: translateY(-2px);
}

.clothes-image {
  width: 100%;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  /* border: 1px solid #f0f0f0; */
  /* border-radius: 4px; */
  box-shadow: 0 0 7px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.clothes-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}

/* .clothes-image:hover img {
  transform: scale(1.05);
} */

/* 空状态 */
.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 0;
  color: #999999;
}

.empty-state img {
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

/* 加载状态 */
.loading-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 0;
  color: #999999;
}

/* 响应式设计 */
/* @media (max-width: 768px) {
  .secondary-categories {
    width: 30%;
  }

  .clothes-grid {
    width: 70%;
    padding: 12px;
    gap: 12px;
  }

  .header {
    padding: 12px 16px;
  }

  .title {
    font-size: 16px;
  }

  .sub-category-item {
    padding: 12px 8px;
    font-size: 13px;
  }

  .clothes-item {
    padding: 6px;
  }
}

@media (max-width: 480px) {
  .secondary-categories {
    width: 35%;
  }

  .clothes-grid {
    width: 65%;
    gap: 8px;
    padding: 8px;
  }

  .clothes-item {
    padding: 4px;
  }
} */
</style>
